package com.guapi.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.guapi.annotation.SelfController;
import com.guapi.dao.Conversation;
import com.guapi.dao.ResponseData;
import com.guapi.dao.User;
import com.guapi.exception.SelfException;
import com.guapi.service.ConversationService;
import com.guapi.util.ConversationConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@SelfController
@RequestMapping("/message")
@ResponseBody
public class ConversationController extends BaseController<Conversation> implements ConversationConstant {

    @Autowired
    private ConversationService conversationService;

    @RequestMapping("/user")
    public ResponseData loginUserMessage(HttpServletRequest request) {
        //此处还要有很多东西，如果太多就塞进service
        Conversation conversation = new Conversation();
        conversation.setConversationId(getLoginUser().getId() + DOWN_LINE);
        List<Conversation> toList = conversationService.getByFuzzy(conversation);
        conversation.setConversationId(DOWN_LINE + getLoginUser().getId());
        List<Conversation> fromList = conversationService.getByFuzzy(conversation);

        toList.addAll(fromList);
        List<Conversation> conversationList = CollectionUtil.sortByProperty(toList, "createDate");
        List<Conversation> tmpUserConversation = conversationList.stream().filter(con -> ObjectUtil.equals(con.getType(), USER_MESSAGE)).collect(Collectors.toList());
        List<List<Conversation>> userConversation = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(tmpUserConversation)) {
            userConversation = conversationService.packageConversation(tmpUserConversation);
            int count = userConversation.stream().mapToInt(List::size).sum();
            responseData.setData("userMessage", userConversation);
            responseData.setTotal((long) count);
        }
        List<Conversation> systemList = conversationList.stream().filter(con -> ObjectUtil.equals(con.getType(), SYSTEM_MESSAGE)).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(systemList)) {
            responseData.setData("systemMessage", systemList);
            responseData.setTotal(responseData.getTotal() == 0 ? 0 : responseData.getTotal() + systemList.size());
        }
        responseData.setSuccess(true);
        return responseData;
    }

    @RequestMapping("/send")
    public ResponseData sendMessage(HttpServletRequest request, @RequestBody Map messageMap) {
        responseData = new ResponseData();
        try {
            User loginUser = getLoginUser();
            Object toUser = messageMap.get("toUser");
            User user = BeanUtil.mapToBean((Map<?, ?>) toUser, User.class, true, null);
            conversationService.sendConversation(messageMap, loginUser.getId(), user.getId());
        } catch (Exception e) {
            throw new SelfException("消息处理异常,请联系管理员");
        }
        responseData.setSuccess(true);
        return responseData;
    }

    @RequestMapping("/unread")
    public ResponseData getUnreadCount(HttpServletRequest request, @RequestBody Map typeMap) {
        Conversation conversation = new Conversation();
        int unreadCount = 0;
        responseData = new ResponseData();
        if (!typeMap.containsKey(GET_UNREAD_BY_ID) && !typeMap.containsKey(GET_UNREAD_BY_USER) || CollectionUtil.isEmpty(typeMap)) {
            //若无具体指定，则查询登录用户的所有未读消息
            conversation.setStatus(0);
            conversation.setToId(getLoginUser().getId());
            unreadCount = conversationService.getByConditions(conversation).size();
        } else if (typeMap.containsKey(GET_UNREAD_BY_ID) && typeMap.containsKey(GET_UNREAD_BY_USER)) {
            throw new SelfException("条件重复，请不要同时输入会话ID以及会话人信息");
        } else if (typeMap.containsKey(GET_UNREAD_BY_ID)) {
            conversation.setConversationId(String.valueOf(typeMap.get(GET_UNREAD_BY_ID)));
            unreadCount = conversationService.getByConditions(conversation).size();
        } else if (typeMap.containsKey(GET_UNREAD_BY_USER)) {
            conversation.setFromId((Integer) typeMap.get(GET_UNREAD_BY_USER));
            unreadCount = conversationService.getByConditions(conversation).size();
        }
        responseData.setTotal((long) unreadCount);
        responseData.setSuccess(true);
        return responseData;
    }

    @RequestMapping("/read")
    public void setConversationRead(HttpServletRequest request, @RequestBody Conversation conversation) {
        conversationService.setConversationRead(conversation.getConversationId());
    }

    @RequestMapping("/list")
    public ResponseData list(HttpServletRequest request, @RequestBody Map map) {
        startPage(map);
        List<Conversation> conversations;
        Map searchStr = (Map) map.get("searchStr");
        String fromId = "";
        String toId = "";
        String content = "";
        if (searchStr != null) {
            fromId = (String) searchStr.get("searchFrom");
            toId = (String) searchStr.get("searchTo");
            content = (String) searchStr.get("searchContent");
        }
        Conversation conversation = new Conversation();
        if (StrUtil.isAllEmpty(fromId, toId, content)) {
            conversations = conversationService.list();
        } else {
            if (StrUtil.isNotEmpty(fromId)) {
                conversation.setFromId(Integer.valueOf(fromId));
            }
            if (StrUtil.isNotEmpty(toId)) {
                conversation.setToId(Integer.valueOf(toId));
            }
            if (StrUtil.isNotEmpty(content)) {
                conversation.setContent(content);
            }
            conversations = conversationService.getByFuzzy(conversation);
        }

        responseData.setRows(conversations);
        responseData.setSuccess(true);
        return responseData;
    }

}
